package example.fileupload;

import com.google.protobuf.ByteString;
import example.fileuplaod2.FileUploadClient;
import grpc.htsoft.fileupload.*;

import grpc.htsoft.fileupload2.FileChunk;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class fileclient4 {
    public static void main(String[] argc) throws IOException {
        System.out.println("Hello, fileclient4!");
        FileServiceGrpc.FileServiceStub fileServiceStub;
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50092)
                .usePlaintext()
                .build();
        fileServiceStub = FileServiceGrpc.newStub(channel);

//        StreamObserver<FileUploadRequest> streamObserver = fileServiceStub.upload(new FileUploadObserver());


        StreamObserver<FileUploadResponse> responseObserver = new StreamObserver<FileUploadResponse>() {
            @Override
            public void onNext(FileUploadResponse value) {
                System.out.println(value.getName());
            }

            @Override
            public void onError(Throwable t) {
                t.printStackTrace();
            }

            @Override
            public void onCompleted() {


                System.out.println("File upload completed.");
                channel.shutdownNow();
            }
        };
        StreamObserver<FileUploadRequest> streamObserver = fileServiceStub.upload(responseObserver);
//        Path path = Paths.get("/Users/zgw/image/0.png");
//        FileUploadRequest metadata = FileUploadRequest.newBuilder()
//                .setMetadata(MetaData.newBuilder()
//                        .setName("output3")
//                        .setType("png").build())
//                .build();
//        streamObserver.onNext(metadata);

//        InputStream inputStream = Files.newInputStream(path);
        String path = "/Users/zgw/image/0.png";
        FileInputStream inputStream = new FileInputStream(path);
        byte[] bytes = new byte[4096];
        int size;
        while ((size = inputStream.read(bytes)) > 0){
            FileUploadRequest uploadRequest = FileUploadRequest.newBuilder()
                    .setFile(File.newBuilder().
                            setContent(ByteString.copyFrom(bytes, 0 , size)).build())
                    .build();
            streamObserver.onNext(uploadRequest);
        }
        inputStream.close();
        streamObserver.onCompleted();
        try {
            channel.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
